package com.tianze.library.base;

import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.tianze.library.R;
import com.tianze.library.adapter.recycler.RecyclerBaseAdapter;

import butterknife.ButterKnife;

/**
 * Created by kingtami.
 */
public abstract class BaseRecyclerFragment extends BaseFragment implements RecyclerBaseAdapter.OnItemClickListener, RecyclerBaseAdapter.OnItemLongClickListener {

    protected RecyclerView mRecyclerView;
    protected LinearLayoutManager mLayoutManager;
    protected RecyclerBaseAdapter mAdapter;

    @Override
    protected int getLayoutId() {
        return R.layout.tiza_fragment_recycler;
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initView() {
        mLayoutManager = getLayoutManager();
        mRecyclerView = ButterKnife.findById(rootView, R.id.recycler_view);

        if (isNeedListDivider()) {
            mRecyclerView.addItemDecoration(
                    new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST));
        }
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setHasFixedSize(true);

        if (mAdapter != null) {
            mRecyclerView.setAdapter(mAdapter);
        } else {
            mAdapter = getListAdapter();
            mAdapter.setOnItemClickListener(this);
            mAdapter.setOnItemLongClickListener(this);
            mRecyclerView.setAdapter(mAdapter);
        }
    }

    protected LinearLayoutManager getLayoutManager() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        return layoutManager;
    }

    @Override
    public void onItemClick(View view) {
        onItemClick(view, mRecyclerView.getChildPosition(view));
    }

    protected void onItemClick(View view, int position) {
    }

    @Override
    public boolean onItemLongClick(View view) {
        return onItemLongClick(view, mRecyclerView.getChildPosition(view));
    }

    protected boolean onItemLongClick(View view, int position) {
        return false;
    }

    protected abstract RecyclerBaseAdapter getListAdapter();

    protected void notifyDataSetChanged() {
        if (mAdapter != null)
            mAdapter.notifyDataSetChanged();
    }

    protected boolean isNeedListDivider() {
        return true;
    }
}
